#! /usr/bin/python
# -*- coding: utf-8 -*-

import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import urllib
import conf
import utils
import paper
import papernavbar
import restutil
import xnuser

class MainPage(webapp.RequestHandler):
    def get(self):
        cookieDict = utils.getXnCookieDict(self.request.cookies)
        is_logged_in = utils.validateXnCookies(cookieDict, conf.app_secret)
        profile_owner = self.request.get('id')
        callback_url = utils.getUrlPathQuery(self.request)
        if not is_logged_in:
            self.redirect("/login?" + urllib.urlencode({'url':callback_url}))
            return None
        xnuid = cookieDict['user']
        
        try:
            xnuidInt = int(xnuid)
        except ValueError:
            xnuidInt = 0
        xnuser.getAndUpdateUserData(xnuidInt, cookieDict.get('session_key'))
        
        #restClient = restutil.rest(cookieDict.get('session_key'))
        #testText = restClient.usersGetInfo([240650143,int(xnuid)], ['name','tinyurl_with_logo','headurl_with_logo','mainurl_with_logo'])
        
        if not profile_owner:
            profile_owner = xnuid
        if profile_owner == xnuid:
            is_me = True
        else:
            is_me = False
        nav = self.request.get('nav')
        category = utils.getCategoryByNav(nav)
        errMsg = ''
        try:
            profile_owner = int(profile_owner)
        except ValueError:
            profile_owner = 0
            errMsg = '参数错误，请联系管理员'
        paperNavbar = papernavbar.getPaperNavbar(self.request)        
        paperList = []
        xnName = None
        xnMainPhotoWithLogo = None
        if not errMsg:
            if not category or category == 'all':
                paperList = paper.listPapersByAuthor(profile_owner, paperNavbar['offset'], paperNavbar['limit'], is_me)
            else:
                paperList = paper.listPapersByAuthorCategory(profile_owner, category, paperNavbar['offset'], paperNavbar['limit'], is_me)
            for paperModel in paperList:
                paperModel.catText = utils.getCategoryTextByValue(paperModel.category)
            xnUserModel = xnuser.getXnUserById(profile_owner)
            if xnUserModel:
                xnName = xnUserModel.name
                xnMainPhotoWithLogo = xnUserModel.mainurl_with_logo
        template_values = {
            'staticUrl': conf.staticUrl,
            'jsVersion': conf.jsVersion,
            'cssVersion': conf.cssVersion,
            'api_key': conf.api_key,
            'xnuid': xnuid,
            'isLoggedIn': is_logged_in,
            'xiaoneiProfilePrefix': conf.xiaoneiProfilePrefix,
            'profile_owner': profile_owner,
            'is_me': is_me,
            'session_key': cookieDict['session_key'],
            'new_paper_link': '发表新文章',
            'navRssLink': '订阅Ta的文章',
            'sysPaperUrlCelebrating': conf.sysPaperUrlCelebrating,
            'sysPaperUrlFaq': conf.sysPaperUrlFaq,
            'sysPaperUrlSiteEvents': conf.sysPaperUrlSiteEvents,
            'sysPaperUrlHowToRss': conf.sysPaperUrlHowToRss,
            'paperCategoryList': conf.paperCategoryList,
            'navPath': 'profile',
            'nav_selected': nav,
            'errMsg': errMsg,
            'paperList': paperList,
            'xnName': xnName,
            'xnMainPhotoWithLogo': xnMainPhotoWithLogo,
            'notShowAuthor': True,
            'ShowDraftMark': True,
            'paperNavbar': paperNavbar,
            'paperStatusNormal': paper.paperStatusNormal,
            'callback_url': callback_url
        }
        path = os.path.join(os.path.dirname(__file__), 'pages/profile.html')
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/profile', MainPage)],
                                     debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
